﻿//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2021 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------

using GameFramework;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using Excel;
using System.Data;
using System.Text;

namespace ProjectMG.Editor.DataTableTools
{
    public sealed class DataTableGeneratorMenu
    {
        private static readonly string m_DataTablePath = "Assets/GameMain/DataTables";
        private static readonly string m_DataTableListFileName = "Assets/GameMain/DataTables/DataTableList.txt";
        private static readonly List<string> m_DataTableNames = new List<string>();

        [MenuItem("ProjectMGTools/DataTableTools/生成数据表解析类和数据文件")]
        private static void GenerateDataTables()
        {
            try
            {
                if (File.Exists(m_DataTableListFileName))
                {
                    File.WriteAllText(m_DataTableListFileName, string.Empty);
                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh();
                }
            }
            catch (Exception exception)
            {
                Debug.LogWarning(exception);
            }
            m_DataTableNames.Clear();

            string dataTablesPath = Application.dataPath.Replace("Client/Project/Assets", "_DataTable");
            DirectoryInfo dirInfo = new DirectoryInfo(dataTablesPath);
            FileInfo[] excelFiles = dirInfo.GetFiles("*.xlsx", SearchOption.AllDirectories);
            foreach (FileInfo excelFile in excelFiles)
            {
                try
                {
                    string dataTableName = Path.GetFileNameWithoutExtension(excelFile.Name);
                    IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(File.Open(dataTablesPath + @"\" + excelFile.Name, FileMode.Open, FileAccess.Read, FileShare.Read));
                    DataSet dataSet = reader.AsDataSet();//讲excel中的内容读成DataSet的形式
                    ReadTableToTxt(dataTableName, dataSet.Tables[0]);//这里注意传进去的文件名带.xlsx后缀，要在函数中处理一下
                    AssetDatabase.Refresh();

                    //添加到DataTableLis
                    m_DataTableNames.Add(dataTableName);
                    m_DataTableNames.Sort();

                    //生成数据表代码和二进制数据表
                    GenerateDataTableCodeFilesAndBytesFiles(dataTableName);
                }
                catch (IOException err)
                {
                    Debug.LogError("文件" + excelFile.Name + "被占用，请先关闭");
                    Debug.LogError(err.Message);
                }

                //string filepath = Utility.Path.GetRegularPath(Path.Combine(dataTablesPath, excelFile.Name));
                //CopyAndRenameFile(filepath, m_DataTablePath);
            }

            File.WriteAllBytes(m_DataTableListFileName, Utility.Converter.GetBytes(string.Join("\r\n", m_DataTableNames.ToArray())));
            AssetDatabase.Refresh();
        }

        private static void ReadTableToTxt(string dataTableName, DataTable table)
        {
            string savedFilePath = m_DataTablePath + @"\" + dataTableName + ".txt";
            if (File.Exists(savedFilePath))
            {
                File.Delete(savedFilePath);
            }

            using (FileStream fs = new FileStream(savedFilePath, FileMode.Create))
            {
                using (StreamWriter sw = new StreamWriter(fs, Encoding.Unicode))
                {
                    for (int row = 0; row < table.Rows.Count; row++)
                    {
                        DataRow dataRow = table.Rows[row];
                        string str = "";
                        for (int col = 0; col < table.Columns.Count; col++)
                        {
                            string val = dataRow[col].ToString();
                            str += val + "\t";
                        }
                        sw.Write(str);
                        if (row != table.Rows.Count - 1)
                        {
                            sw.WriteLine();
                        }
                    }
                }
            }
        }

        private static void CopyAndRenameFile(string sourceFilePath, string destinationDirectory)
        {
            string dataTableName = Path.GetFileNameWithoutExtension(sourceFilePath);
            string directoryPath = Path.GetDirectoryName(destinationDirectory);
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            // 修改文件扩展名
            string newExtension = ".txt";
            string destinationFilePath = Path.Combine(destinationDirectory, Path.GetFileName(sourceFilePath));
            destinationFilePath = Path.ChangeExtension(destinationFilePath, newExtension);

            //复制文件
            File.Copy(sourceFilePath, destinationFilePath, true);

            //添加到DataTableLis
            m_DataTableNames.Add(dataTableName);
            m_DataTableNames.Sort();

            //生成数据表代码和二进制数据表
            GenerateDataTableCodeFilesAndBytesFiles(dataTableName);
        }

        private static void GenerateDataTableCodeFilesAndBytesFiles(string dataTableName)
        {
            DataTableProcessor dataTableProcessor = DataTableGenerator.CreateDataTableProcessor(dataTableName);
            if (!DataTableGenerator.CheckRawData(dataTableProcessor, dataTableName))
            {
                Debug.LogError(Utility.Text.Format("Check raw data failure. DataTableName='{0}'", dataTableName));
                return;
            }

            DataTableGenerator.GenerateDataFile(dataTableProcessor, dataTableName);
            DataTableGenerator.GenerateCodeFile(dataTableProcessor, dataTableName);
        }
    }
}
